package model.data.database;

/**
 * AccountTable.java
 * Purpose: Represents an account.
 * 
 * @author Hans Brems
 * @version 0.2 24/01/2012
 */

import java.util.ArrayList;
import java.util.List;

import model.Customer;
import model.data.CustomerStore;

public class CustomerTable implements CustomerStore {
	/* Handles requests to the database */
	DatabaseHandler dbHandler;
	
	/** Constructs a new customer table */
	public CustomerTable() {
		this.dbHandler = new DatabaseHandler();
	}
	
	/** Writes a new customer to the table */
	@Override
	public void write(Customer customer) throws Exception {
		this.dbHandler.callUpdateProcedure("sp_insertcustomer(?,?,?)", customer.getName(), customer.getAddress(), customer.getAccount().getId());
	}

	@Override
	public void update(Customer customer) {
		// TODO Auto-generated method stub
	}

	@Override
	public void delete(Customer customer)  throws Exception{
		this.dbHandler.callUpdateProcedure("sp_deletecustomer(?)", customer.getId());
	}

	@Override
	public int getCount() throws Exception {
		int count = 0;
		ArrayList<DataRecord> records;

		// Get records
		records = (ArrayList<DataRecord>)this.dbHandler.callQueryProcedure("sp_getcountcustomer");
		
		// Fill list
		for (DataRecord dr : records) {
			count = Integer.parseInt(dr.getValue("Result"));
		}
		
		// Return result
		return count;
		
	}

	@Override
	public List<Customer> getById(long id) throws Exception {
		ArrayList<Customer> customers;
		ArrayList<DataRecord> records;
		
		// Get records
		records = (ArrayList<DataRecord>)this.dbHandler.callQueryProcedure("sp_getbyidcustomer(?)", id);
		
		// Create list
		customers = new ArrayList<Customer>();
		
		// Fill list
		for (DataRecord dr : records) {
			Customer customer = new Customer();
			customer.setId(Long.parseLong(dr.getValue("CustomerID")));
			customer.setName(dr.getValue("Name"));
			customer.setAddress(dr.getValue("Address"));
			customer.setAccountId(Long.parseLong(dr.getValue("AccountId")));
			customers.add(customer);
		}
		
		// Return result
		return customers;
	}
}